/**
 * Copyright 2010 Creative Works, Inc.
 * Creative Works licenses this file to you under the Apache License, version
 * 2.0 (the "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *    http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
 * implied.  See the License for the specific language governing
 * permissions and limitations under the License.
 */
package org.sendvox.freswitch.core.impl;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.replay.ReplayingDecoder;
import org.sendvox.freswitch.event.impl.RawMessage;
import org.sendvox.freswitch.util.Arguments;

public class EventSocketLibDecoder extends
		ReplayingDecoder<EventSocketLibDecoder.DecodingState> {

	private final Logger logger = Logger.getLogger(EventSocketLibDecoder.class
			.getName());

	protected static enum DecodingState {
		ESL_MSG_HEADER, ESL_MSG_BODY;
	}

	private final int maxHeaderSize;
	private final boolean treatUnknownHeadersAsBody;

	public EventSocketLibDecoder(int maxHeaderSize) {
		this(maxHeaderSize, false);
	}

	public EventSocketLibDecoder(int maxHeaderSize,
			boolean treatUnknownHeadersAsBody) {
		super(DecodingState.ESL_MSG_HEADER);
		Arguments.INSTANCE.validate(maxHeaderSize).isPositive();
		this.maxHeaderSize = maxHeaderSize;
		this.treatUnknownHeadersAsBody = treatUnknownHeadersAsBody;
	}

	private RawMessage currentMessage;

	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer, DecodingState state) throws Exception {

		switch (state) {
		case ESL_MSG_HEADER:

			if (currentMessage == null) {
				currentMessage = new RawMessage();
			}

			// this will read or fail
			new EventSocketLibDigest().extractSocketResponseHeader(
					currentMessage, buffer, maxHeaderSize,
					treatUnknownHeadersAsBody);

			checkpoint();

			/*
			 * If one of the name/value pairs is a Content-Length header, you
			 * need to read exactly that many bytes from the socket after the
			 * initial headers and two CRLF's are encountered.
			 */
			if (currentMessage.hasContentLength()) {
				checkpoint(DecodingState.ESL_MSG_BODY);
				return null;
			} else {
				checkpoint(DecodingState.ESL_MSG_HEADER);
				RawMessage decodedMessage = currentMessage;
				currentMessage = null;
				return decodedMessage;
			}

		case ESL_MSG_BODY:

			int contentLength = currentMessage.getContentLength();
			logger.log(Level.INFO, "read [" + buffer.writerIndex()
					+ "] body bytes");
			ChannelBuffer bodyBytes = buffer.readBytes(contentLength);

			new EventSocketLibDigest().extractSocketResponseBody(
					currentMessage, bodyBytes, contentLength);

			// end of message
			checkpoint(DecodingState.ESL_MSG_HEADER);
			// send message upstream
			RawMessage decodedMessage = currentMessage;
			currentMessage = null;

			return decodedMessage;

		default:
			throw new Error("Illegal state: [" + state + ']');
		}

	}

}
